//
//  UserAccountViewModel.swift
//  RacWeibo
//
//  Created by zimu on 15/10/26.
//  Copyright © 2015年 hanxu. All rights reserved.
//

import UIKit
import ReactiveCocoa

class UserAccountViewModel: NSObject {
    ///用户账户
    var userAccount : UserAccount?
    
    ///singleton
    static let sharedUserAccount = UserAccountViewModel()
    
    override init() {
        
        userAccount = UserAccount.loadUserAccount()
    }
    

    
    ///MARK: - 网络请求
    ///加载 token & 个人信息
        //doNext 是可以给信号增加附加操作，第一个信号完成之后，将第一个信号的 result 直接传递给第二个信号
        //doNext 后面一定要加一个 subscriberXXX，否则 doNext 不会被执行到
        //doNext 是被动的, subscriber 是主动的订阅
    func loadUserInfo(code: String) -> RACSignal {
        
        return RACSignal.createSignal { (subscriber) -> RACDisposable! in
            
            NetworkTools.sharedTools.loadAccessToken(code).doNext { (result) -> Void in
                
                let account = UserAccount(dict: result as! [String : AnyObject])
                self.userAccount = account
//                
//                NetworkTools.sharedTools.loadUserInfo(account.access_token!, uid: account.uid!).subscribeNext({ (result) -> Void in
//                    self.userAccount = UserAccount(dict: result as! [String: AnyObject])
//                    self.userAccount?.saveUserAccount()
//                    subscriber.sendCompleted()
//                })
                NetworkTools.sharedTools.loadUserInfo(account.access_token!, uid: account.uid!).doNext({ (result) -> Void in
                    self.userAccount = UserAccount(dict: result as! [String : AnyObject])
                    self.userAccount?.saveUserAccount()
                    //结束信号
                    subscriber.sendCompleted()
                    
                }).subscribeError({ (error) -> Void in
                    subscriber.sendError(error)
                })
                }.subscribeError { (error) -> Void in
                    subscriber.sendError(error)
            }
        }
    }
}

